const pool = require("./db.js");

class ExamineGroupsDao {
    async addExamineGroups(groupId, userId) {
        const [rows, fields] = await pool.execute(
            "INSERT INTO examine_groups (group_id, user_id) VALUES (?, ?)",
            [groupId, userId]
        );
        return rows;
    }

    async deleteExamineGroupsByGroupID(groupId) {
        const [rows, fields] = await pool.execute(
            "DELETE FROM examine_groups WHERE group_id = ?",
            [groupId]
        );
        return rows;
    }

    async deleteExamineGroups(examine_group_id) {
        const [rows, fields] = await pool.execute(
            "DELETE FROM examine_groups WHERE examine_group_id = ?",
            [examine_group_id]
        );
        return rows;
    }
    async selectExamineGroupsByGroupID(start, rows, GroupID) {
        console.log('start:'+start,'rows'+rows,'GroupID:'+GroupID);
        let sql1 = `SELECT DISTINCT * FROM examine_groups where group_id=? limit ${start}, ${rows}`;
        let sql2 = `SELECT COUNT(1) AS rowCount FROM examine_groups where group_id=? `;
        const [rows1,fields1] = await pool.execute(sql1,[GroupID]);
        const [rows2,fields2] = await pool.execute(sql2,[GroupID]);
        
        const rowCount = rows2[0]['rowCount'];
        const pageCount = Math.ceil(rowCount / rows);
    
        return { 
            data: Array.isArray(rows1) ? rows1 : [], 
            rowCount:rowCount, 
            pageCount:pageCount 
        };
    }
    async selectExamineGroupsByUserID(userId) {
        const [rows, fields] = await pool.execute(
            "SELECT DISTINCT * FROM examine_groups WHERE user_id = ?",
            [userId]
        );
        return rows;
    }

    async selectExamineGroupsByGroupIDAndUserID(GroupID, UserID) {
        const [rows, fields] = await pool.execute(
            "SELECT DISTINCT * FROM examine_groups WHERE group_id = ? AND user_id = ?",
            [GroupID, UserID]
        );
        return rows;
    }
}

module.exports = new ExamineGroupsDao();